import * as departmentApi from '@/api/department'

const state = {
  departmentList: []
}

const mutations = {
  SET_DEPARTMENT_LIST(state, newValue) {
    state.departmentList = newValue
  }
}

const actions = {
  async updateDepartmentList({ commit }) {
    const res = await departmentApi.getDepartmentList()
    commit('SET_DEPARTMENT_LIST', res)
  }
}

function tranfrom(data, pid) {
  return data.filter(d => d.pid === pid)
  .map(i => ({
    ...i,
    id: i.id,
    children: tranfrom(data, i.id)
  }))
}

const getters = {
  amendDepartment(state) {
    return tranfrom(state.departmentList, '')
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
}
